package com.bicon.botu.mall.member.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.member.dto.AttentionCatDTO;
import com.bicon.botu.mall.member.dto.AttentionDTO;
import com.bicon.botu.mall.member.dto.AttentionReconmmendDTO;
import com.bicon.botu.mall.member.service.IAttentionService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.mall.member.common.MemberConstants;
import com.bicon.botu.mall.member.dto.CouponsDto;
import com.bicon.botu.mall.member.entity.Attention;
import com.bicon.botu.mall.member.mapper.AttentionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

import static com.alibaba.fastjson.JSON.parseArray;

/**
 * @Author 李双喜
 * @Date 2017/7/22 11:43
 */
@Slf4j
@Service
@Transactional
public class AttentionServiceImpl extends ServiceImpl<AttentionMapper, Attention> implements IAttentionService {
    @Autowired
    private AttentionMapper attentionMapper;
   /**
     * 我的关注降价排序（根据userId查询）
     *
     * @param userId 用户id
     * @return
     */
    /*
    @Override
    public BaseResult selectAllAttention(String userId) {
        List<AttentionDTO> attentionDTOList = attentionMapper.selectAllAttention(userId);
        if (!attentionDTOList.isEmpty() && null != attentionDTOList) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, attentionDTOList);
        }
        return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
    }*/



    /**
     * 我的关注 取消关注的（根据单个或多个Id的逻辑删除）  批量删除
     */
    @Override
    public BaseResult deleteAttention(String attentionIdJson) {
        //用逗号分割，数组接收
        String[] ids = attentionIdJson.split(",");
        //判断
        if (ids.length <= 0) {
            return new BaseResult(MemberConstants.RESPONSE_CODE_401, MemberConstants.RESPONSE_MESSAGE_401);
        }
        List<Attention> attentionArrayList = new ArrayList<>();
        //将数组遍历
        for (String id : ids) {
            Attention attention = attentionMapper.selectById(id);
            if (null == attention) {
                return new BaseResult(MemberConstants.RESPONSE_CODE_404, MemberConstants.RESPONSE_MESSAGE_404);
            }
            attention.setLogicDelete(Constants.DEL_LOGIC_DELETE);
            attention.preUpdate();
            attentionArrayList.add(attention);//根据多个id修改后，放入list集合，做批量删除
        }
        //这个this就是AttentionServiceImpl
        //这个updateBatchById专门做批量
        boolean result = this.updateBatchById(attentionArrayList);
        if (result) {
            return new BaseResult(MemberConstants.RESPONSE_CODE_200, MemberConstants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(MemberConstants.RESPONSE_CODE_500, MemberConstants.RESPONSE_MESSAGE_500);
    }

    /**
     * 看相似（根据商品分类相似和价格相似查询）
     */
    @Override
    public Page<AttentionReconmmendDTO> selectResemble(String categoryId, BigDecimal price, Integer pageNo, Integer pageSize) {
        Page<AttentionReconmmendDTO> page = new Page<>(pageNo, pageSize);
        Map<String, Object> map = new HashMap<>();
        //将double转为BigDecimal
        BigDecimal similarPrice = new BigDecimal(MemberConstants.SIMILARPRICE);
        //BigDecimal作加减
        BigDecimal priceUpper = price.add(similarPrice);
        BigDecimal priceLower = price.subtract(similarPrice);

        map.put("categoryId", categoryId);
        map.put("priceUpper", priceUpper);
        map.put("priceLower", priceLower);
        List<AttentionReconmmendDTO> attentionReconmmendDTOList = attentionMapper.selectResemble(map, page);
        //判断不为空
        if (!attentionReconmmendDTOList.isEmpty() && null != attentionReconmmendDTOList) {
            page.setRecords(attentionReconmmendDTOList);//把集合放入分页里面
        }
        return page;
    }
    /**
     * 默认排序,降价排序，促销排序
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public BaseResult selectDefaultAttention(String userId) {
        List<AttentionDTO> attentionDTOList = attentionMapper.selectAttention(userId);
        //1.查出所有在发行期内的优惠卷
        List<CouponsDto>couponsDtoList = attentionMapper.selectAllCoupons();
        //2.调用 校验优惠券方法
        List<CouponsDto> couponlist;
        for (AttentionDTO attentionDTO:attentionDTOList){
            couponlist = this.verify(couponsDtoList,attentionDTO.getProductId(), attentionDTO.getBrandId(),attentionDTO.getProductId());
            //3.集合siz（）大于0 设置type = 1， 小于0 设置type = 0
            if (null != couponlist && couponlist.size() > 0) {
                attentionDTO.setType("1");
            } else {
                attentionDTO.setType("0");
            }
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, attentionDTOList);
    }



    /**
     * 查询所有的关注商品
     */
    @Override
    public BaseResult selectAttention(String userId) {
        List<AttentionDTO> attentionDTOList = attentionMapper.selectAttention(userId);
        if (!CollectionUtils.isEmpty(attentionDTOList)){
            return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200,attentionDTOList);
        }
        return null;
    }



    /**
     * 校验优惠券
     *
     * @param couponsDtoList  优惠券集合
     * @param classifyPath    分类path
     * @param brandId         品牌id
     * @param productId       商品id
     * @return
     */
    private List<CouponsDto> verify(List<CouponsDto> couponsDtoList, String classifyPath, String brandId, String productId) {
        List<CouponsDto> resultList = new ArrayList<CouponsDto>();
        for (CouponsDto entity : couponsDtoList) {
            if (null != classifyPath) {
                if (entity.getPath().contains(classifyPath)) {
                    resultList.add(entity);
                }
            }
            if (null != brandId) {
                if (entity.getPath().equals(brandId)) {
                    resultList.add(entity);
                }
            }
            if (null != productId) {
                if (entity.getPath().contains(productId)) {
                    resultList.add(entity);
                }
            }
        }
        if (resultList.size() > 0) {
            return resultList;
        } else {
            return null;
        }
    }


    /**
     * 我的关注--为你推荐
     * @param categoryIdJson   多个商品类目Id
     * @return
     */

    @Override
    public BaseResult selectAttentionRecommend(String categoryIdJson) {
/*        //JSON转List
        List<String> list = JSONObject.parseArray(categoryIdJson,String.class);*/
       if (StringUtils.isEmpty(categoryIdJson)){
           return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200);
       }
       List<AttentionReconmmendDTO> attentionReconmmendDTOS = new ArrayList<>();
        String[] categoryIds = categoryIdJson.split(",");
        for(int i =0;i<categoryIds.length;i++){
            List<AttentionReconmmendDTO> list = attentionMapper.selectAttentionRecommend(categoryIds[i]);
            attentionReconmmendDTOS.addAll(list);
        }
         return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200,attentionReconmmendDTOS);
    }

    /**
     * 批量添加关注
     * @param userId         用户id
     * @param attentionJson  关注json
     * @return
     */
    @Override
    public String insertAttention(String userId, String attentionJson) {
        //将多个attentionJson转为List
        List<AttentionCatDTO> list = parseArray(attentionJson,AttentionCatDTO.class);
        List<Attention> list1 = new ArrayList<>();
        //遍历list
        if (null != list) {
            List<String> stringList = new ArrayList<>();
            for (AttentionCatDTO attentionCatDTO : list) {
                if (StringUtils.isNotEmpty(attentionCatDTO.getProductId())) {
                    stringList.add(attentionCatDTO.getProductId());
                }
            }
            if (null != stringList && stringList.size()>0) {
                List<Attention> attentionList = new Attention().selectList(new EntityWrapper<Attention>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("user_id", userId).in("product_id", stringList));
                if (null != attentionList && attentionList.size() > 0) {
                    for (Attention attention : attentionList) {
                        attention.preUpdate();
                        attention.setLogicDelete(Constants.DEL_LOGIC_DELETE);
                    }
                    this.updateBatchById(attentionList);
                }
            }
        }
        //遍历list
        StringBuffer id = new StringBuffer();
        for (AttentionCatDTO dto:list){
            Attention attention = new Attention().selectOne(new EntityWrapper<Attention>().eq("product_id",dto.getProductId()).
                    eq("user_id",userId).eq("product_repertory_id",dto.getProductRepertoryId()).eq("logic_delete",Constants.DEL_LOGIC_NORMAL));
            if(null!=attention){
                if(attention.getId()!=null && !"".equals(attention.getId())){
                    list1.add(attention);
                }
            }else {
                Attention attention1 = new Attention();
                attention1.setUserId(userId);
                attention1.setProductRepertoryId(dto.getProductRepertoryId());
                attention1.setAttentionPrice(new BigDecimal(dto.getAttentionPrice()));
                attention1.setProductId(dto.getProductId());
                attention1.preInsert();
                list1.add(attention1);
                id.append(attention1.getId()).append(",");
            }
        }
          boolean result= this.insertOrUpdateBatch(list1);
        if (result){
            return id.toString();
        }
         return null;
    }
}
